from cou.api_1_0 import api
from cou.models import Area,Taocan
from flask import jsonify,request,current_app
from cou.utils.response_code import RET
from cou.eleme_spider import ele_spider
from cou.utils.constants import TAOCAN_NUM
@api.route('/taocans')
def get_taocans():
    aid=request.args.get('aid')
    sd=request.args.get('sd')
    ed=request.args.get('ed')
    sk=request.args.get('sk')
    try:
        page=int(request.args.get('p'))
    except Exception as e:
        page=1
        current_app.logger.error(e)
    
    filters=[]
    if aid:
        filters.append(Taocan.area_id==aid)
    if sd:
        try:
            sd=int(float(sd)*100)
        except Exception as e:
            current_app.logger.error(e)
        else:
            filters.append(Taocan.price>sd)
    if ed:
        try:
            ed=int(float(ed)*100)
        except Exception as e:
            current_app.logger.error(e)
        else:
            filters.append(Taocan.price<ed)
    sort_key=None
    if sk == 'new':
        sort_key=Taocan.create_time.desc()
    elif sk == 'booking':
        sort_key=Taocan.check_time.desc()
    elif sk =='price-inc':
        sort_key=Taocan.price
    elif sk =='price-des':
        sort_key=Taocan.price.desc()
    else:
        sort_key=Taocan.create_time.desc()

    try:
        paginate=Taocan.query.filter(*filters).order_by(sort_key).paginate(page,TAOCAN_NUM,False)
    except Exception as e:
        current_app.logger.error(e)
    pages=paginate.pages
    taocans=paginate.items
    
    
    taocans_return=[]
    for i in taocans:
        taocans_return.append(i.to_detail())
    return jsonify(errno=RET.OK,errmsg="成功",data={'total_page':pages,'taocans':taocans_return})

    
